'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');
const utils = require('../utils/utils');

class UserController extends Controller {
  async messageCode() {
    const { ctx } = this;
    const { phone } = ctx.request.query;
    const msgCode = utils.getLengthRandom(6);
    ctx.session.msgCode = msgCode;
    ctx.body = {
      code: 1,
      message: `验证码[ ${msgCode} ]已发送至手机 [ ${phone} ]`,
    };
  }

  async info() {
    const { ctx } = this;
    ctx.body = {
      code: 1,
      data: ctx.userInfo,
    };
  }

  async login() {
    const { ctx } = this;
    const { code, phone } = ctx.request.body;
    if (code === ctx.session.msgCode) {
      const user = await ctx.service.user.find(phone);
      if (user) {
        const token = jwt.sign({ ...user }, 'liuyu001');
        ctx.cookies.set('token', token, {
          maxAge: 1000 * 60 * 60 * 24 * 30,
          httpOnly: false,
        });
        ctx.body = {
          code: 1,
          message: '登录成功',
          // token,
        };
      } else {
        // 自动注册一个用户，并且登录成功
        ctx.throw(422, '用户不存在');
      }
    } else {
      ctx.throw(422, '验证码错误');
    }
  }
}

module.exports = UserController;
